"use strict";
/* Controllers */
app.controller("basicDimController", ['$scope', '$location', '$rootScope', '$routeParams', 'zhaopinzheDimService', '$q', function ($scope, $location, $rootScope, $routeParams, zhaopinzheDimService, $q) {
    var vm = $scope.vm = {};

    vm.p = {};
    vm.result = {};
    vm.p.biz = '58';
    vm.p.appDiv = $routeParams.appdiv;
    // vm.p.appDiv = 'zhaopinzhe';

    var datePicker = $('.date');
    datePicker.datetimepicker({
        locale: 'zh-cn',
        format: 'YYYY-MM-DD'
    });
    datePicker.on('dp.hide', function (e) {
        var currentInput = $(e.currentTarget).find('input');
        var eName = currentInput.attr('name');
        var p = $scope.vm.p;
        p[eName] = currentInput.val();
        $scope.$apply()
    });

    if ($scope.vm.p.bizTime == '' || typeof ($scope.vm.p.bizTime) == 'undefined') {
        $scope.vm.p.bizTime = new Date(new Date().getTime() - 86400000).format('yyyy-MM-dd');
    }

    var errorFn = function (result) {
        alert(result);
    };

    $scope.listDashboardDimData = function () {
        $("#list_table").bootstrapTable('showLoading')
        var vm = $scope.vm;
        vm.result.ms = '...';
        var params = vm.p;
        var procFn = function (response) {
            vm.result = response;
            var data = response.data;
            if (data == null) {
                alert("暂无数据" + response.message);
                // alert("请求失败：" + response.message);
                $('#list_table').bootstrapTable('hideLoading');
                $("#refreshTable").removeClass('disabled');
                return;
            }

            vm.dashboardDimData = data;
            $scope.getDimTableByDimId();
            $('#list_table').bootstrapTable('hideLoading');
            $("#refreshTable").removeClass('disabled');
        };
        return zhaopinzheDimService.listDashboardDimData(params, procFn, errorFn);
    };


    $scope.listDapanDimConfig = function () {
        $("#list_table").bootstrapTable('showLoading')
        var vm = $scope.vm;
        var params = vm.p;
        var procFn = function (response) {
            $("#list_table").bootstrapTable('hideLoading')
            vm.result = response;
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }

            if (data.length > 0) {
                $scope.vm.dimConfigData = data
                $scope.changeDim()
            }
        }
        return zhaopinzheDimService.listDapanDimConfig(params, procFn, errorFn);
    };

    $scope.changeDim = function () {
        var dimArr = [];
        let biz = $scope.vm.p.biz
        let dimConfigData = $scope.vm.dimConfigData
        for (var i = 0; i < dimConfigData.length; ++i) {
            var element = dimConfigData[i];
            if (element.biz == biz) {
                var dimObj = {};
                dimObj.dimId = element.dimId;
                dimObj.dimNameCn = element.dimNameCn;
                dimObj.dimName = element.dimName
                dimArr.push(dimObj);
            }
        }
        $scope.vm.dimArr = dimArr
        vm.p.dimId = vm.dimArr[0].dimId;
    }

    // $scope.initTables = function () {
    //     $scope.$apply();
    //     var dashboardDimData = $scope.vm.dashboardDimData;
    //     for (var i in dashboardDimData) {
    //         var item = dashboardDimData[i];
    //         var columns = [];
    //         for (var k in item.columnNames) {
    //             var element = item.columnNames[k];
    //             var column = {};
    //             column.title = element;
    //             column.field = element;
    //             column.sortable = true;
    //             columns.push(column)
    //         }
    //         columns[0].width = 100;
    //         var tableData = item.tableData;
    //         var $table = $("#list_table_" + item.configId);
    //         $table.bootstrapTable('destroy').bootstrapTable({
    //             columns: columns,
    //             data: tableData
    //         })
    //     }
    // };

    $scope.getDimTableByDimId = function () {
        var $table = $("#list_table");
        if ($scope.vm.dashboardDimData.length == 0) {
            $table.bootstrapTable('destroy');
            return;
        }

        var dimData = $scope.vm.dashboardDimData

        let dimIndex = $scope.vm.p.dimId.split('^').length
        var columns = [];
        var columnNames = dimData.columnNames;
        let sortName
        for (var k = 0; k < columnNames.length; ++k) {
            var element = columnNames[k];
            var column = {};
            column.title = element;
            column.field = element;
            column.sortable = true;
            if (k > dimIndex) {
                column.formatter = operateFormatter
            }
            if (k == dimIndex + 1) {
                sortName = element
            }
            columns.push(column)
        }
        columns[0].width = 100;

        var indexMap = {}
        if (dimData && dimData.indexEn && dimData.indexCn) {
            var indexEnArr = dimData.indexEn.split(",")
            var indexCnArr = dimData.indexCn.split(",")
            for (let index = 0; index < indexEnArr.length; index++) {
                const curEn = indexEnArr[index];
                const curCn = indexCnArr[index];
                indexMap[curCn] = curEn
            }
        }
        $scope.vm.indexMap = indexMap

        var tableData = dimData.tableData;
        $table.bootstrapTable('destroy').bootstrapTable({
            exportDataType: 'all',
            exportTypes: ['excel', 'json', 'xml', 'csv', 'txt'],
            columns: columns,
            sortOrder: 'desc',
            sortName: sortName,
            data: tableData
        })
    };

    function operateFormatter(value, row, index, field) {
        let dimObj = $scope.vm.dimArr.find(function (x) {
            return x.dimId == $scope.vm.p.dimId
        })

        let dimNameArr = dimObj.dimName.split('^')
        let dimNameCnArr = dimObj.dimNameCn.split('^')
        let dimValue = []
        let dimValueCn = []
        for (let index = 0; index < dimNameArr.length; index++) {
            let curdimName = dimNameArr[index]
            let curDimNameCn = dimNameCnArr[index]
            dimValue.push(row[curdimName])
            dimValueCn.push(row[curDimNameCn])

        }

        let curIndexCn = field
        let curIndexEn = $scope.vm.indexMap[field]


        let clickFncStr = "angular.element(this).scope().toIndexChart('" + dimObj.dimId + "', '" + dimValue.join('^') + "', '" + curIndexEn + "', '" + curIndexCn + "','" + dimValueCn.join('^') + "')"
        return [
            '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
            numberFmt(value),
            '</a>  ',
        ].join('')
    }

    $scope.toIndexChart = function (dimId, dimValue, curIndexEn, curIndexCn, dimValueCn) {

        console.log(dimId + '\n' + dimValue + '\n' + curIndexEn + '\n' + curIndexCn)

        var params = {};
        params.dimId = dimId
        params.dimValue = dimValue
        params.dimValueCn = dimValueCn
        params.indexEn = curIndexEn
        params.indexCn = curIndexCn
        params.biz = $scope.vm.p.biz


        var dom = document.getElementById('dapan_chart');
        var myChart = echarts.init(dom);
        myChart.showLoading()
        vm.result.ms = '...';
        var procFn = function (response) {
            vm.result = response;
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            let modalTitle = ''
            let dimIdArr = data.dimId.split('^')
            let dimValueArr = data.dimValueCn.split('^')
            for (let index = 0; index < dimIdArr.length; index++) {
                let curDimId = dimIdArr[index];
                let dimObj = $scope.vm.dimArr.find(function (x) {
                    return x.dimId == curDimId
                })
                let curDimValue = dimValueArr[index];
                modalTitle = modalTitle + dimObj.dimNameCn + ':' + curDimValue + ' '
            }

            $scope.vm.modalTitle = modalTitle

            initChart(myChart, data.chartData, data.indexCn)
            myChart.hideLoading()
        };
        zhaopinzheDimService.getDimIndexChart(params, procFn, errorFn);

        $('#myModal').modal('show')
    }

    function initChart(myChart, data, title) {

        var dateList = data.map(function (item) {
            return item[0];
        });
        var valueList = data.map(function (item) {
            return item[1];
        });
        // var dom = document.getElementById("container");

        window.onresize = function () {
            myChart.resize();
        };
        var option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'cross' }
            },
            legend: {
            },
            dataZoom: [{}],
            xAxis: {
                type: 'category',
                data: dateList
            },
            yAxis: [
                {
                    name: '指标值',
                    type: 'value'
                }
            ],
            series: [
                {
                    name: title,
                    yAxisIndex: 0,
                    data: valueList,
                    type: 'line',
                    smooth: true
                }
            ]
        };
        window.onresize = function () {
            myChart.resize();
        };
        if (option && typeof option === 'object') {
            myChart.setOption(option);
        }
    }

    $scope.queryDashboard = function () {
        $("#refreshTable").addClass('disabled');
        $scope.listDashboardDimData();
    };

    $scope.listDapanDimConfig().then(function () {
        $scope.queryDashboard();
    })



}]);

// function tableLoadingTemplate(message) {
//     return '<i class="fa fa-spinner fa-spin fa-fw fa-2x"></i>'
// }



//自定义指令实现ng-repeat完成后执行repeatFinish方法
//app.directive('myRepeatFinish', function () {
//    return {
//        restrict: 'A',
//        link: function (scope, element, attr) {
//            console.log(scope.$index);
//            if (scope.$last == true) {
//                console.log('ng-repeat over, will draw chart.');
//                scope.$eval(attr.myRepeatFinish)
//            }
//        }
//    }
//});

/* Services */
app.service('zhaopinzheDimService', ['ajaxService', function (ajaxService) {

    //    this.listCoreMetrics = function (params, successFunction, errorFunction) {
    //        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listCoreMetrics.do", successFunction, errorFunction);
    //    };
    //    this.listChartMetrics = function (params, successFunction, errorFunction) {
    //        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listAllMetricSeries.do", successFunction, errorFunction);
    //    };
    this.listDashboardDimData = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listDashboardDimData.do", successFunction, errorFunction);
    };

    this.getDimIndexChart = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/getDimIndexChart.do", successFunction, errorFunction);
    };

    this.listDapanDimConfig = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/web_dapan/listDapanDimConfig.do", successFunction, errorFunction);
    };


}]);

